//
//  MainPageViewController.m
//  MobileShoppingMall
//
//  Created by 冯传昌 on 2021/4/13.
//  Copyright © 2021 冯传昌. All rights reserved.
//

#import "MainPageViewController.h"

#import "MainPageGoodsCell.h"

#import "MainPageHeaderView.h"

#import "MainPageHeaderModel.h"

#import "GoodTypesCell.h"

#import "MainPageGoodsModel.h"

@interface MainPageViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>

@property (nonatomic,strong) MainPageHeaderView *topHeaderView;//顶部背景view
@property (nonatomic,strong) UITableView *tableView;//tableView

@property (nonatomic,strong) GeneralNavSearchView *topNavView;//顶部搜索框 默认alpha 0

@property (nonatomic,strong) NSMutableArray *headerGoodTypesArr;//顶部商品类型数组

@property (nonatomic,strong) NSMutableArray *headerBannerArr;//顶部banner数组

@property (nonatomic,strong) NSMutableArray *dataSourceArr;//数据源数组

@property (nonatomic,assign) NSInteger currentPage;//当前页数   初始值 1

@property (nonatomic,assign) BOOL isRefreshing;//当前页面是否正在刷新

@property (nonatomic,copy) NSString *currentSearchProductName;//当前搜索商品名

@end

@implementation MainPageViewController

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    [self loadTopHeaderData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.headerGoodTypesArr = [NSMutableArray array];
    self.headerBannerArr = [NSMutableArray array];
    
    self.dataSourceArr = [NSMutableArray array];
    self.isRefreshing = NO;
    self.currentPage = 1;
    
    [self initUI];
    [self getNewData];
}

#pragma mark - data
-(void)loadTopHeaderData{
    self.headerGoodTypesArr = [NSMutableArray array];
    self.headerBannerArr = [NSMutableArray array];
    WEAKSELF(self);
    [NetWorkingShop getTBShopInfoWithSuccessBlock:^(id  _Nonnull responseObj) {
        NSDictionary *data = responseObj[@"data"];
        NSArray *types = data[@"types"];
        NSArray *banners = data[@"productcarouses"];
        for (NSDictionary *dic in types) {
            MainPageHeaderModel *model = [MainPageHeaderModel mj_objectWithKeyValues:dic];
            model.Id = [[dic objectForKey:@"id"] integerValue];
            [weakSelf.headerGoodTypesArr addObject:model];
        }
        for (NSDictionary *dic in banners) {
            MainPageHeaderModel *model = [MainPageHeaderModel mj_objectWithKeyValues:dic];
            model.Id = [[dic objectForKey:@"id"] integerValue];
            [weakSelf.headerBannerArr addObject:model];
        }
        weakSelf.topHeaderView.bannerSourceArr = weakSelf.headerBannerArr;
        NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:0];
        [weakSelf.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
    }];
}
-(void)getNewData{
    [NetWorkingShop getTBShopListWithPage:self.currentPage WithSuccessBlock:^(id  _Nonnull responseObj) {
        self.dataSourceArr = [NSMutableArray array];
        NSDictionary *data = responseObj[@"data"];
        NSArray *records = data[@"records"];
        for (NSDictionary *dic in records) {
            MainPageGoodsModel *model = [MainPageGoodsModel mj_objectWithKeyValues:dic];
            model.ID = [dic[@"id"] integerValue];
            [self.dataSourceArr addObject:model];
        }
        [self.tableView reloadData];
        
        [self delayLoadRefreshStatus];
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self delayLoadRefreshStatus];
    });
}
-(void)getMoreData{
    [NetWorkingShop getTBShopListWithPage:self.currentPage WithSuccessBlock:^(id  _Nonnull responseObj) {
        NSDictionary *data = responseObj[@"data"];
        NSArray *records = data[@"records"];
        for (NSDictionary *dic in records) {
            MainPageGoodsModel *model = [MainPageGoodsModel mj_objectWithKeyValues:dic];
            model.ID = [dic[@"id"] integerValue];
            [self.dataSourceArr addObject:model];
        }
        [self.tableView reloadData];
        
        [self delayLoadRefreshStatus];
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self delayLoadRefreshStatus];
    });
}
//搜索数据
-(void)getSearchData:(NSString *)searchStr{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"type"] = @"1";
    params[@"typeId"] = @"";
    params[@"name"] = searchStr;
    self.currentPage = 1;
    [NetWorkingShop getShopSearchListWithPage:self.currentPage withParams:params WithSuccessBlock:^(id  _Nonnull responseObj) {
        self.dataSourceArr = [NSMutableArray array];
        NSDictionary *data = responseObj[@"data"];
        NSArray *records = data[@"records"];
        for (NSDictionary *dic in records) {
            MainPageGoodsModel *model = [MainPageGoodsModel mj_objectWithKeyValues:dic];
            model.ID = [dic[@"id"] integerValue];
            [self.dataSourceArr addObject:model];
        }
        [self.tableView reloadData];
        [self delayLoadRefreshStatus];
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self delayLoadRefreshStatus];
    });
}
//延迟刷新
-(void)delayLoadRefreshStatus{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        self.isRefreshing = NO;
    });
}
#pragma mark - setter
- (void)setIsRefreshing:(BOOL)isRefreshing{
    _isRefreshing = isRefreshing;
    [self.view setUserInteractionEnabled:!_isRefreshing];
    self.tableView.scrollEnabled = !_isRefreshing;
}
-(void)reloadSearchDataWithSearchStr:(NSString *)searchStr{
    self.topNavView.searchStr = _currentSearchProductName;
    self.topHeaderView.searchStr = _currentSearchProductName;
    if (_currentSearchProductName.length <= 0) {
        [self getNewData];
    }else{
        //搜索商品
        [self getSearchData:_currentSearchProductName];
    }
}

#pragma mark - UI
-(void)initUI{
    WEAKSELF(self);
    [_topHeaderView setUpdateHeightBlock:^(CGFloat height) {
        weakSelf.topHeaderView.height = height;
    }];
    [self.view addSubview:self.tableView];
    [self.tableView setTableHeaderView:self.topHeaderView];
    [self.view addSubview:self.topNavView];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if (self.isRefreshing == NO) {
            self.isRefreshing = YES;
            self.currentPage = 1;
            [self.tableView.mj_header beginRefreshing];
            [self getNewData];
        }
    }];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        if (self.isRefreshing == NO) {
            self.isRefreshing = YES;
            self.currentPage = self.currentPage + 1;
            [self.tableView.mj_footer beginRefreshing];
            [self getMoreData];
        }
    }];
}
-(void)viewBlocks{
    WEAKSELF(self);
    [self.topNavView setSearchBlock:^(NSString * _Nonnull searchString) {
        weakSelf.currentSearchProductName = searchString;
        [weakSelf reloadSearchDataWithSearchStr:searchString];
    }];
    [self.topHeaderView setSearchEventBlock:^(NSString * _Nonnull searchString) {
        weakSelf.currentSearchProductName = searchString;
        [weakSelf reloadSearchDataWithSearchStr:searchString];
    }];
}
#pragma mark - lazy
- (GeneralNavSearchView *)topNavView{
    if (!_topNavView) {
        _topNavView = [[GeneralNavSearchView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, kHeight_NavBar)];
        _topNavView.alpha = 0;
        [_topNavView setShowMenuBlock:^{
        }];
    }
    return _topNavView;
}

-(MainPageHeaderView *)topHeaderView{
    if (!_topHeaderView) {
        _topHeaderView = [[MainPageHeaderView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenWidth*0.45)];
        _topHeaderView.backgroundColor = UIColor.whiteColor;
    }
    return _topHeaderView;
}
//tableView
-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, -kHeight_StatusBar-5, ScreenWidth, ScreenHeight-kHeight_TabBar+kHeight_StatusBar+5) style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = UIColor.clearColor;
    }
    return _tableView;
}
#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 1) {
        return self.dataSourceArr.count;
    }
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        return 170*Width_Scale;
    }else{
        return 60;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return 64;
    }else{
        return 0.1f;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1f;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return nil;
    }
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth-20, 64)];
    view.backgroundColor = Color_Clear;
    
    UIImageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake(20, 17, 30, 30)];
    imgV.image = LoadImage(@"首页_TB");
    [view addSubview:imgV];
    
    UILabel *lb = [[UILabel alloc] initWithFrame:CGRectMake(imgV.right+5, imgV.top, 110, 30)];
    lb.textColor = RGB(253, 155, 49);
    lb.font = FontSetWithWeight(23, 0.4f);
    lb.textAlignment = NSTextAlignmentCenter;
    lb.text = @"TB商品区";
    [view addSubview:lb];
    
    UIImageView *moreImgV = [[UIImageView alloc] initWithFrame:CGRectMake(lb.right+5, 23, 18, 18)];
    moreImgV.image = LoadImage(@"首页_TB更多");
    [view addSubview:moreImgV];
    return view;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        MainPageGoodsModel *model = self.dataSourceArr[indexPath.row];
        MainPageGoodsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainPageGoodsCell"];
        if (!cell) {
            cell = [[MainPageGoodsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MainPageGoodsCell"];
        }
        cell.model = model;
        return cell;
    }else{
        GoodTypesCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GoodTypesCell"];
        if (!cell) {
            cell = [[GoodTypesCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"GoodTypesCell"];
        }
        cell.sourceArr = self.headerGoodTypesArr;
        [cell setTouchBlock:^(NSInteger touchIndex) {
            [self headerTouchClick:touchIndex];
        }];
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        MainPageGoodsModel *model = self.dataSourceArr[indexPath.row];
        GoodsDetailsViewController *vc = [[GoodsDetailsViewController alloc] init];
        vc.goodsModel = model;
        vc.goodsID = model.ID;
        [self.navigationController pushViewController:vc animated:YES];
    }
}
#pragma mark - SEL
//顶部条目点击事件
-(void)headerTouchClick:(NSInteger)touchIndex{
    if (self.headerGoodTypesArr.count <= touchIndex) {
        return;
    }
    MainPageHeaderModel *model = self.headerGoodTypesArr[touchIndex];
    if ([model.name isEqualToString:@"手机充值"]) {
        [JumpManager jumpToReplenishingVC];
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView.contentOffset.y > kHeight_NavBar) {
        self.topNavView.alpha = 1;
    }else if (scrollView.contentOffset.y <= 0 ){
        self.topNavView.alpha = 0;
    }else{
        self.topNavView.alpha = scrollView.contentOffset.y/kHeight_NavBar;
    }
}

@end


